#setup.py
from distutils.core import setup
from distutils.extension import Extension
import os
import sys

def check_include(directory, include):
    try:
        open(os.path.join(directory, include))
    except IOError:
        return False
    return True

udunits_dir = os.environ.get('UDUNITS_DIR')
udunits_incdir = os.environ.get('UDUNITS_INCDIR')
udunits_libdir = os.environ.get('UDUNITS_LIBDIR')

boost_dir = os.environ.get('BOOST_DIR')
boost_incdir = os.environ.get('BOOST_INCDIR')
boost_libdir = os.environ.get('BOOST_LIBDIR')
boost_mt = os.environ.get('BOOST_MT')

directories =  [os.path.expanduser('~'),
                '/usr/local',
                '/sw',
                '/opt',
                '/opt/local',
                '/usr']
setup_cfg = 'setup.cfg'

if os.path.exists(setup_cfg):
    sys.stdout.write('reading from setup.cfg...\n') 
    config = configparser.SafeConfigParser()
    config.read(setup_cfg)

    try: udunits_dir = config.get("directories", "udunits_dir")
    except: pass

    try: udunits_incdir = config.get("directories", "udunits_incdir")
    except: pass

    try: udunits_libdir = config.get("directories", "udunits_libdir")
    except: pass

    try: boost_dir = config.get("directories", "boost_dir")
    except: pass

    try: boost_incdir = config.get("directories", "boost_incdir")
    except: pass

    try: boost_libdir = config.get("directories", "boost_libdir")
    except: pass

    try: boost_mt = config.get("options", "boost_mt")
    except: pass

if udunits_dir is None and udunits_incdir is None:
    sys.stdout.write("\nUDUNITS_DIR environment variable not set, "
                     "checking some standard locations ..\n""")
    for directory in directories:
        sys.stdout.write('checking %s ...\n' % directory)
        found = check_include(os.path.join(directory, 'include'), 'udunits2.h')
        if not found:
            continue
        else:
            udunits_dir = directory
            udunits_incdir = os.path.join(directory, 'include')
            sys.stdout.write('udunits2 found in %s\n' % udunits_dir)
            break
    if udunits_dir is None:
        raise ValueError('did not find udunits2 headers')
else:
    if udunits_incdir is None:
        udunits_incdir = os.path.join(udunits_dir, 'include')

if boost_dir is None and boost_incdir is None:
    sys.stdout.write("\nBOOST_DIR environment variable not set, "
                     "checking some standard locations ..\n""")
    for directory in directories:
        sys.stdout.write('checking %s ...\n' % directory)
        found = check_include(os.path.join(directory, 'include'),
                              os.path.join('boost', 'python.hpp'))
        if not found:
            continue
        else:
            boost_dir = directory
            boost_incdir = os.path.join(directory, 'include')
            sys.stdout.write('boost found in %s\n' % boost_dir)
            break
    if boost_dir is None:
        raise ValueError('did not find boost headers')
else:
    if boost_incdir is None:
        boost_incdir = os.path.join(boost_dir, 'include')

if udunits_libdir is None and udunits_dir is not None:
    udunits_libdir = os.path.join(udunits_dir, 'lib')

if boost_libdir is None and boost_dir is not None:
    boost_libdir = os.path.join(boost_dir, 'lib')


cpp_files = []
for root, _dirs, files in os.walk('src'):
    for item in files:
        if '.cpp' in item:
            cpp_files.append(os.path.join(root, item))

libs = ['udunits2','boost_python' if not boost_mt else 'boost_python-mt']
lib_dirs = [udunits_libdir, boost_libdir]
inc_dirs = [udunits_incdir, boost_incdir]

extensions = [Extension("udunits2",
                        cpp_files,
                        libraries=libs,
                        library_dirs=lib_dirs,
                        include_dirs=inc_dirs,
                        runtime_library_dirs=lib_dirs)]

setup(name = "udunits2",
  version = "1.0",
  long_description = "Python wrapper for udunits2 library.",
  author            = "Frederic Briol",
  author_email      = "fbriol@cls.fr",
  url               = "http://netcdf4-python.googlecode.com/svn/trunk/docs/netCDF4-module.html",
  download_url      = "http://code.google.com/p/netcdf4-python/downloads/list",
  platforms         = ["any"],
  license           = "OSI Approved",
  description = "Provides an object-oriented python interface to the udunits version 2 library.",
  keywords = ['udunits2','data','science', 'oceanography','meteorology','climate'],
  classifiers = ["Development Status :: 3 - Alpha",
                 "Intended Audience :: Science/Research", 
                 "License :: OSI Approved", 
                 "Topic :: Software Development :: Libraries :: Python Modules",
                 "Operating System :: OS Independent"],
  ext_modules = extensions)
